<template>
  <view class="order-list">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-bg"></view>
      <view class="header-content">
        <view class="page-title">我的订单</view>
        <view class="page-subtitle">查看和管理您的订单信息</view>
      </view>
    </view>

    <!-- 订单状态标签 -->
    <view class="tabs-container">
      <view class="order-tabs">
        <view 
          v-for="(tab, index) in tabValues" 
          :key="index"
          :class="['tab-item', tabIndex === index ? 'active' : '']"
          @tap="onTabClick(index)"
        >
          <view class="tab-icon">
            <uni-icons :type="getTabIcon(index)" size="20" :color="tabIndex === index ? '#667eea' : '#999'"></uni-icons>
          </view>
          <text class="tab-text">{{ tab }}</text>
          <view v-if="getTabBadge(index) > 0" class="tab-badge">{{ getTabBadge(index) }}</view>
        </view>
      </view>
    </view>
    
    <!-- 订单列表 -->
    <view class="content-container">
      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !isLoading" class="empty-state">
        <view class="empty-icon">
          <uni-icons type="list" size="80" color="#bdc3c7"></uni-icons>
        </view>
        <text class="empty-title">暂无订单</text>
        <text class="empty-desc">您还没有任何订单，去购物吧</text>
        <button class="empty-btn" @click="goShopping">
          <uni-icons type="shop" size="16" color="#fff"></uni-icons>
          <text class="empty-btn-text">去购物</text>
        </button>
      </view>

      <!-- 订单项 -->
      <view v-else class="order-items">
        <view v-for="(order, index) in orderList" :key="index" class="order-card">
          <!-- 订单头部 -->
          <view class="order-header">
            <view class="order-info">
              <view class="order-id">
                <uni-icons type="list" size="14" color="#7f8c8d"></uni-icons>
                <text class="order-id-text">{{ order.trade_no || 'ORD' + (Date.now() + index) }}</text>
              </view>
              <view class="order-time">{{ order.create_time || '2023-12-01 10:30' }}</view>
            </view>
            <view class="order-status" :class="[getStatusClass(order.trade_status)]">
              <uni-icons :type="getStatusIcon(order.trade_status)" size="16" color="#fff"></uni-icons>
              <text class="status-text">{{ getStatusText(order) }}</text>
            </view>
          </view>
          
          <!-- 商品列表 -->
          <view class="order-goods">
            <view v-for="(item, idx) in getOrderGoods(order)" :key="idx" class="goods-item">
              <image :src="item.image || '/static/images/default-goods.png'" mode="aspectFill" class="goods-image"></image>
              <view class="goods-info">
                <text class="goods-name">{{ item.goods_name || '商品名称' }}</text>
                <text class="goods-spec">{{ item.goods_spec || '规格信息' }}</text>
                <view class="goods-price-section">
                  <text class="goods-price">¥{{ parseFloat(item.goods_price || 0).toFixed(2) }}</text>
                  <text class="goods-quantity">×{{ item.goods_quantity || 1 }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 订单底部 -->
          <view class="order-footer">
            <view class="order-summary">
              <text class="summary-text">共{{ getOrderGoodsCount(order) }}件商品</text>
              <view class="total-section">
                <text class="total-label">合计:</text>
                <text class="total-price">¥{{ parseFloat(order.payment_amount || getRandomPrice()).toFixed(2) }}</text>
              </view>
            </view>
            
            <view class="order-actions">
              <button 
                v-if="canViewDetail(order)" 
                class="action-btn secondary" 
                @tap="viewOrderDetail(order.order_id || index)"
              >
                查看详情
              </button>
              <button 
                v-if="canCancel(order)" 
                class="action-btn danger" 
                @tap="cancelOrder(order.order_id || index)"
              >
                取消订单
              </button>
              <button 
                v-if="canPay(order)" 
                class="action-btn primary" 
                @tap="payOrder(order.order_id || index)"
              >
                <uni-icons type="wallet" size="16" color="#fff"></uni-icons>
                <text class="btn-text">立即付款</text>
              </button>
              <button 
                v-if="canUploadReceipt(order)" 
                class="action-btn warning" 
                @tap="uploadReceipt(order.order_id || index)"
              >
                <uni-icons type="camera" size="16" color="#fff"></uni-icons>
                <text class="btn-text">上传回执</text>
              </button>
              <button 
                v-if="canConfirm(order)" 
                class="action-btn success" 
                @tap="confirmReceive(order.order_id || index)"
              >
                确认收货
              </button>
              <button 
                v-if="canEvaluate(order)" 
                class="action-btn warning" 
                @tap="evaluateOrder(order.order_id || index)"
              >
                <uni-icons type="star" size="16" color="#fff"></uni-icons>
                <text class="btn-text">评价</text>
              </button>
              <button 
                v-if="canRefund(order)" 
                class="action-btn info" 
                @tap="refundOrder(order.order_id || index)"
              >
                申请退款
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { getOrderList, cancelOrder, confirmReceive, getOrderStats,getOrderUserList } from '@/api/order'

export default {
  data() {
    return {
      activeTab: 'all',
      orderList: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      tabIndex: 0,
      tabValues: ['全部', '待付款', '待发货', '待收货', '已完成'],
      isLoading: false,
      orderStats: {}, // 订单统计数据
      // 订单状态映射
      statusMap: {
        '0': '待付款',
        '1': '已支付',
        '2': '已发货',
        '3': '已送达',
        '4': '已签收',
        '5': '已完成',
        '6': '已取消',
        'pending': '待付款',
        'paid': '已支付',
        'shipped': '已发货',
        'delivered': '已送达',
        'received': '已签收',
        'completed': '已完成',
        'cancelled': '已取消',
        'offline_pending': '等待回执',
        'offline_receipt_uploaded': '回执已上传',
        'offline_payment_confirmed': '付款已确认'
      }
    }
  },
  
  onLoad(options) {
    if (options.type) {
      this.activeTab = options.type
      // 根据type设置对应的tab
      const statusMap = ['all', 'waitPay', 'waitShip', 'waitReceive', 'waitEvaluate']
      this.tabIndex = statusMap.indexOf(options.type)
    }
    // this.getOrderStats()
  },
  
  onShow() {
    this.getOrderUserList(true)
  },
  
  onReachBottom() {
    if (this.hasMore && !this.isLoading) {
      this.page++
      this.getOrderUserList(false)
    }
  },
  
  methods: {
    // 获取订单统计数据
    async getOrderStats() {
      try {
        const response = await getOrderStats()
        if (response && response.data) {
          this.orderStats = response.data
        }
      } catch (error) {
        this.orderStats = {
          pending: 0,
          shipped: 0,
          completed: 0,
          cancelled: 0
        }
      }
    },
    
    onTabClick(index) {
      this.tabIndex = index
      const statusMap = ['all', 'waitPay', 'waitShip', 'waitReceive', 'waitEvaluate']
      this.activeTab = statusMap[index]
      this.getOrderUserList(true)
    },
    
    async getOrderUserList(refresh = false) {
      if (refresh) {
        this.page = 1
        this.hasMore = true
      }
      
      this.isLoading = true
      
      try {
        const response = await getOrderUserList({
          status: this.activeTab,
          page: this.page,
          page_size: this.pageSize
        })
        
        // 匹配API返回的数据结构
        const { orders, total, page, page_size, total_pages } = response.data
        
        if (refresh) {
          this.orderList = orders || []
        } else {
          this.orderList = [...this.orderList, ...(orders || [])]
        }
        
        // 判断是否还有更多数据
        this.hasMore = page < total_pages
        
      } catch (error) {
        uni.showToast({
          title: error.message || '获取订单列表失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取标签图标
    getTabIcon(index) {
      const icons = ['list', 'wallet', 'star', 'home', 'star']
      return icons[index] || 'list'
    },
    
    // 获取标签徽章数量
    getTabBadge(index) {
      if (!this.orderStats) return 0
      
      const badgeMap = {
        1: this.orderStats.waitPay || 0,    // 待付款
        3: this.orderStats.waitReceive || 0, // 待收货  
        4: this.orderStats.waitEvaluate || 0  // 待评价
      }
      return badgeMap[index] || 0
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const statusClassMap = {
        '0': 'status-wait-pay',
        '1': 'status-paid',
        '2': 'status-shipped', 
        '3': 'status-delivered',
        '4': 'status-received',
        '5': 'status-completed',
        '6': 'status-cancelled',
        'pending': 'status-wait-pay',
        'paid': 'status-paid',
        'shipped': 'status-shipped', 
        'delivered': 'status-delivered',
        'received': 'status-received',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled',
        'offline_pending': 'status-offline-pending',
        'offline_receipt_uploaded': 'status-receipt-uploaded',
        'offline_payment_confirmed': 'status-payment-confirmed'
      }
      return statusClassMap[status] || 'status-default'
    },
    
    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        '0': 'wallet',
        '1': 'checkmarkempty',
        '2': 'car',
        '3': 'location',
        '4': 'home',
        '5': 'star-filled',
        '6': 'close',
        'pending': 'wallet',
        'paid': 'checkmarkempty',
        'shipped': 'car',
        'delivered': 'location',
        'received': 'home',
        'completed': 'star-filled',
        'cancelled': 'close',
        'offline_pending': 'compose',
        'offline_receipt_uploaded': 'camera-filled',
        'offline_payment_confirmed': 'checkmarkempty'
      }
      return iconMap[status] || 'list'
    },
    
    // 获取状态文本
    getStatusText(order) {
      if (order.trade_status && this.statusMap[order.trade_status]) {
        return this.statusMap[order.trade_status]
      }
      // 如果没有状态信息，根据索引生成
      const fallbackTexts = ['已完成', '待付款', '待发货', '待收货', '待评价']
      return fallbackTexts[Math.floor(Math.random() * fallbackTexts.length)]
    },
    
    // 获取订单商品 - 直接使用API返回的数据
    getOrderGoods(order) {
      return order.goods_list || []
    },
    
    // 获取订单商品数量
    getOrderGoodsCount(order) {
      return order.goodsCount || order.goods_list?.length || 0
    },
    
    // 获取随机价格
    getRandomPrice() {
      return (Math.random() * 500 + 50).toFixed(2)
    },
    
    // 权限判断方法
    canViewDetail(order) { 
      return true 
    },
    
    canCancel(order) { 
      // 待付款和等待回执状态可以取消
      return ['0', 'pending', 'offline_pending'].includes(order.trade_status)
    },
    
    canPay(order) { 
      // 待付款状态可以支付
      return order.trade_status === '0' || order.trade_status === 'pending'
    },
    
    canConfirm(order) { 
      // 已送达状态可以确认收货
      return order.trade_status === '3' || order.trade_status === 'delivered'
    },
    
    canEvaluate(order) { 
      // 已签收状态可以评价
      return order.trade_status === '4' || order.trade_status === 'received'
    },
    
    canRefund(order) { 
      // 已支付、已发货、已送达状态可以申请退款
      return ['1', '2', '3', 'paid', 'shipped', 'delivered'].includes(order.trade_status)
    },
    
    canUploadReceipt(order) {
      // 线下等待回执状态可以上传回执
      return order.trade_status === 'offline_pending'
    },
    
    viewOrderDetail(id) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${id}`
      })
    },
    
    async cancelOrder(id) {
      try {
        await cancelOrder(id)
        uni.showToast({
          title: '取消成功',
          icon: 'success'
        })
        this.getOrderUserList(true)
      } catch (error) {
        uni.showToast({
          title: '取消失败',
          icon: 'none'
        })
      }
    },
    
    payOrder(id) {
      uni.navigateTo({
        url: `/pages/order/pay?orderId=${id}`
      })
    },
    
    async confirmReceive(id) {
      try {
        await confirmReceive(id)
        uni.showToast({
          title: '确认收货成功',
          icon: 'success'
        })
        this.getOrderUserList(true)
      } catch (error) {
        uni.showToast({
          title: '确认收货失败',
          icon: 'none'
        })
      }
    },
    
    evaluateOrder(id) {
      uni.navigateTo({
        url: `/pages/order/evaluate?orderId=${id}`
      })
    },
    
    refundOrder(id) {
      uni.navigateTo({
        url: `/pages/order/returnApply?orderId=${id}`
      })
    },
    
    uploadReceipt(id) {
      uni.navigateTo({
        url: `/pages/order/uploadReceipt?orderId=${id}`
      })
    },
    
    goShopping() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style scoped>
.order-list {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
}

/* 页面头部 */
.page-header {
  position: relative;
  height: 300rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header-bg::after {
  content: '';
  position: absolute;
  bottom: -2rpx;
  left: 0;
  right: 0;
  height: 40rpx;
  background: #f8f9fa;
  border-radius: 40rpx 40rpx 0 0;
}

.header-content {
  position: relative;
  text-align: center;
  z-index: 2;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

/* 标签页容器 */
.tabs-container {
  background: #fff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.order-tabs {
  display: flex;
  padding: 0 20rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 12rpx;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  transform: translateY(-4rpx);
}

.tab-icon {
  margin-bottom: 8rpx;
}

.tab-text {
  font-size: 24rpx;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

.tab-item.active .tab-text {
  color: #667eea;
  font-weight: 600;
}

.tab-badge {
  position: absolute;
  top: 12rpx;
  right: 20rpx;
  background: linear-gradient(135deg, #ff7675, #d63031);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
  line-height: 1.2;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 2rpx;
}

/* 内容容器 */
.content-container {
  padding: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  background: linear-gradient(135deg, #ddd6fe, #c4b5fd);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 40rpx;
}

.empty-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50rpx;
  border: none;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
}

.empty-btn-text {
  color: #fff;
}

/* 订单列表 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.order-card {
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.order-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.12);
}

/* 订单头部 */
.order-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-bottom: 2rpx solid #f1f3f4;
}

.order-info {
  flex: 1;
}

.order-id {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 8rpx;
}

.order-id-text {
  font-size: 24rpx;
  color: #34495e;
  font-weight: 500;
}

.order-time {
  font-size: 22rpx;
  color: #95a5a6;
}

.order-status {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.status-wait-pay {
  background: linear-gradient(135deg, #fdcb6e, #e17055);
}

.status-wait-ship {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
}

.status-wait-receive {
  background: linear-gradient(135deg, #00b894, #00a085);
}

.status-wait-evaluate {
  background: linear-gradient(135deg, #fd79a8, #e84393);
}

.status-completed {
  background: linear-gradient(135deg, #00cec9, #00b894);
}

.status-paid {
  background: linear-gradient(135deg, #00b894, #00a085);
}

.status-shipped {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
}

.status-delivered {
  background: linear-gradient(135deg, #fdcb6e, #e17055);
}

.status-received {
  background: linear-gradient(135deg, #fd79a8, #e84393);
}

.status-cancelled {
  background: linear-gradient(135deg, #636e72, #2d3436);
}

.status-offline-pending {
  background: linear-gradient(135deg, #a29bfe, #6c5ce7);
}

.status-receipt-uploaded {
  background: linear-gradient(135deg, #ffeaa7, #fdcb6e);
}

.status-payment-confirmed {
  background: linear-gradient(135deg, #55a3ff, #667eea);
}

.status-default {
  background: linear-gradient(135deg, #ddd, #bbb);
}

.status-text {
  color: #fff;
}

/* 商品列表 */
.order-goods {
  padding: 24rpx 32rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 2rpx solid #f8f9fa;
}

.goods-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  background: #f5f5f5;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.goods-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #2c3e50;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.goods-spec {
  font-size: 22rpx;
  color: #7f8c8d;
}

.goods-price-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.goods-price {
  font-size: 28rpx;
  font-weight: 600;
  color: #e74c3c;
}

.goods-quantity {
  font-size: 24rpx;
  color: #95a5a6;
}

/* 订单底部 */
.order-footer {
  padding: 24rpx 32rpx;
  background: #fafbfc;
}

.order-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.summary-text {
  font-size: 24rpx;
  color: #7f8c8d;
}

.total-section {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
}

.total-label {
  font-size: 24rpx;
  color: #34495e;
}

.total-price {
  font-size: 32rpx;
  font-weight: 700;
  color: #e74c3c;
}

/* 操作按钮 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
  flex-wrap: wrap;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  font-size: 22rpx;
  font-weight: 500;
  border: none;
  transition: all 0.3s ease;
  min-width: 120rpx;
  justify-content: center;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
}

.action-btn.secondary {
  background: #f8f9fa;
  color: #6c757d;
  border: 2rpx solid #e9ecef;
}

.action-btn.danger {
  background: linear-gradient(135deg, #ff7675, #d63031);
  color: #fff;
}

.action-btn.success {
  background: linear-gradient(135deg, #00b894, #00a085);
  color: #fff;
}

.action-btn.warning {
  background: linear-gradient(135deg, #fdcb6e, #e17055);
  color: #fff;
}

.action-btn.info {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  color: #fff;
}

.action-btn:active {
  transform: scale(0.95);
}

.btn-text {
  color: inherit;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(102, 126, 234, 0.1);
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 24rpx;
  color: #7f8c8d;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .order-actions {
    justify-content: center;
  }
  
  .action-btn {
    min-width: 100rpx;
    padding: 10rpx 20rpx;
    font-size: 20rpx;
  }
  
  .goods-image {
    width: 100rpx;
    height: 100rpx;
  }
}
</style>    